﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Text.RegularExpressions;
using System.Data.OleDb;


namespace SecurityDev
{
    public partial class SecurityDev : Form
    {
		public delegate void RefreshGrid();
        public SecurityDev()
        {
            InitializeComponent();
            
        }
        FileSystemWatcher _watchFolder = new FileSystemWatcher();

        private void startActivityMonitoring(string sPath)
        {
            // This is the path we want to monitor
            _watchFolder.Path = sPath;
            _watchFolder.Filter = "*.jpg";
            _watchFolder.IncludeSubdirectories = true;

            // Make sure you use the OR on each Filter because we need to monitor
            // all of those activities

            _watchFolder.NotifyFilter = System.IO.NotifyFilters.DirectoryName;

            _watchFolder.NotifyFilter =
            _watchFolder.NotifyFilter | System.IO.NotifyFilters.FileName;
            //_watchFolder.NotifyFilter =
            //_watchFolder.NotifyFilter | System.IO.NotifyFilters.Attributes;

            // Now hook the triggers(events) to our handler (eventRaised)
            _watchFolder.Changed += new FileSystemEventHandler(eventRaised);
            _watchFolder.Created += new FileSystemEventHandler(eventRaised);
            _watchFolder.Deleted += new FileSystemEventHandler(eventRaised);

            // Occurs when a file or directory is renamed in the specific path
            //_watchFolder.Renamed += new System.IO.RenamedEventHandler(eventRenameRaised);

            // And at last.. We connect our EventHandles to the system API (that is all
            // wrapped up in System.IO)
            try
            {
                _watchFolder.EnableRaisingEvents = true;
            }
            catch (ArgumentException)
            {
                
            }
        }
       
        public void insertData(string Path) 
        {

            OleDbConnection sqlConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=../../SecurityDev.accdb");
            {
                string sql = "INSERT INTO AlertsData (ClientName , Priority , Address , DVRIP , AlarmDate, Phone) VALUES('ololo',5, '" + Path + "' , '192.168.1.1' , '12/05/2012', 2495632)";
                sqlConn.Open();
                OleDbCommand command = new OleDbCommand(sql, sqlConn);
                command.ExecuteNonQuery();
                sqlConn.Close();
            };
            alertsDataTableAdapter1.Insert("ololo", 5, Path, "192.168.1.1", "12/05/2012", 2495632);
        }

        private void eventRaised(object sender, System.IO.FileSystemEventArgs e)
        {
			switch (e.ChangeType)
			{
				case WatcherChangeTypes.Created:
					notifyIcon1.ShowBalloonTip(30, "SecureDev",
						string.Format("File {0} has been created\r\n", e.FullPath),
						ToolTipIcon.Warning);
					try
					{
						insertData((string)e.FullPath);
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.ToString());
					}

					break;
				default: // Another action
					break;
			}

			this.Invoke(Delegate.CreateDelegate(typeof(RefreshGrid),this,"refreshGrid"));
            
			/*securityDevDataSet1.Clear();
			securityDevDataSet1.GetChanges();
			alertsDataTableAdapter1.Fill(securityDevDataSet1.AlertsData);			*/
        }

		private void refreshGrid()
		{

            alertsDataTableAdapter1.Fill(securityDevDataSet1.AlertsData);
		}
       
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Maximized;
            }
            this.Activate();
            this.Focus();
        }

        private void SecurityDev_Move(object sender, EventArgs e)
        {
            //This code causes the form to not show up on the task bar only in the tray.
            //NOTE there is now a form property that will allow you to keep the 
            //application from every showing up in the task bar.
            if (this == null)
            { //This happen on create.
                return;
            }
            //If we are minimizing the form then hide it so it doesn't show up on the 
            //task bar
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                notifyIcon1.ShowBalloonTip(30, "SecureDev",
                        "The App has be moved to the tray.",
                        ToolTipIcon.Info);
               
            }
            else
            {//any other windows state show it.
                this.Show();
            }

        }

        private void SecurityDev_FormClosed(object sender, FormClosingEventArgs e)
        {
            if (this.WindowState != FormWindowState.Minimized)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                notifyIcon1.ShowBalloonTip(3000, "SecureDev",
                     "You have not closed this appliation." +
                     (Char)(13) + "It has be moved to the tray." +
                     (Char)(13) + "Right click the Icon to exit.",
                     ToolTipIcon.Warning);
            }
        }
        
        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Maximized;
            }
            this.Activate();
            this.Focus();
        }
        
        private void emailSend_Click(object sender, EventArgs e)
        {
            StreamReader streamReader = new StreamReader("../../index.html");
            string text = streamReader.ReadToEnd();
            text = Regex.Replace(text, "User", "VideOko");
            text = Regex.Replace(text, "link1", "http://cs303106.userapi.com/v303106408/6a39/xeJ_i4rx6JY.jpg");
            text = Regex.Replace(text, "Object_Address", "вул.Шевченка 120");
            streamReader.Close();
            var fromAddress = new MailAddress("siner08@gmail.com", "Dread");
            var toAddress = new MailAddress("videoko@ukr.net", "VideOko");
            const string fromPassword = "Siner100790";
            const string subject = "Alarm Email!";
            string body = text;

            //System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment("C:/Users/Dread/Desktop/aEzoiCECZ58.jpg");

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                IsBodyHtml = true,
                Body = body
            })
                
            {
                //message.Attachments.Add(attachment);
                smtp.Send(message);
                MessageBox.Show("Email sent");
            }
        }

        private void SecurityDev_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'securityDevDataSet1.AlertsData' table. You can move, or remove it, as needed.
            this.alertsDataTableAdapter1.Fill(this.securityDevDataSet1.AlertsData);
            startActivityMonitoring("D:/test/");
        }

        private void selectAllButton_Click(object sender, EventArgs e)
        {
            
        }

        private void MarkGoodButton_Click(object sender, EventArgs e)
        {
			OleDbConnection sqlConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/test/test/SecDev/SecurityDev/SecurityDev/SecurityDev.accdb");
            {
                string sql = "INSERT INTO AlertsData (ClientName , Priority , Address , DVRIP , AlarmDate, Phone) VALUES('ololo',5, 'Shevchenka 5' , '192.168.1.1' , '12/05/2012', 2495632)";
                sqlConn.Open();
                OleDbCommand command = new OleDbCommand(sql, sqlConn);
                command.ExecuteNonQuery();
                sqlConn.Close();
            }
        }
    }
}
